Using Generics in python
Table of Content
Using Generics in python#
Generic is a way to specify the type of data that variable can hold at use time and not when this type declare
from typing import TypeVar, Generic, List, Any
T = TypeVar("T") #(1)
def first(items: List[T]) -> T: #(2)
return items[0]
first_item: int = first([1, 2, 4])
- The
TypeVardeclare thatTcan any type - The function
firstget list of typeTand returnT
Generic class#
from typing import List, Generic, TypeVar
T = TypeVar("T")
class Items(Generic[T]):
def __init__(self) -> None:
self.__data: List[T] = []
def add_item(self, item: T) -> None:
self.__data.append(item)
def first(self) -> T | None:
if self.__data:
return self.__data[0]
return None
if __name__ == "__main__":
items = Items[str]()
items.add_item("a")
other_items = Items[int]()
other_items.add_item(1)
Demo: Generic class with multiple generic types#
from typing import Generic, TypeVar
T = TypeVar("T")
U = TypeVar("U")
class MyClass(Generic[T, U]):
def __init__(self, foo: T, bar: U) -> None:
self.foo = foo
self.bar = bar
def get_foo(self) -> T:
return self.foo
def get_bar(self) -> U:
return self.bar
if __name__ == "__main__":
obj = MyClass[str, int]("name", 10)
print(obj.get_foo())